#!/usr/bin/python
import sys
import XenAPI
import base64
import os
import subprocess
import string
import random

path        = "./"
quotein     = "/tmp/quotein"
aikkey      = path + "aik_pem.pub"
quoteout    = path + "qouteout"
prg         = path + "xenqverify"
noncefile  = path + "nonce"
#./xenqverify  [-c noncefile ] aikrsafile quotein quteout


def doexec(args, inputtext=None):
    """Execute a subprocess, then return its return code, stdout and stderr"""
    proc = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
    (stdout,stderr) = proc.communicate(inputtext)
    rc = proc.returncode
    return (rc,stdout,stderr)

def call_exec():
    rc = 0
    (rc,stdout,stderr) = doexec([prg,"-c", noncefile, aikkey,quotein,quoteout])
    return rc


def main(session):

    hostlist = session.xenapi.host.get_all()
    hid = 1
    if (len(hostlist) > 1):
        print "\t ## Pool host label names ##\n"
        for x in hostlist:
            print "\t"+session.xenapi.host.get_name_label(x)
        hid = int(raw_input('\n which host?? (enter no from 1)   ::'))
        if ( (hid < 1)  and (hid > (len(hostlist))) ) :
            print "range is 1 to %d" %len(hostlist)
            sys.exit(1)
    host_ref = hostlist[hid-1]
    #host_ref = session.xenapi.session.get_this_host(session.handle)

    # generate a 20 bytes random nonce
    # the nonce can be arbitrary long tough
    try:
        lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(20)]
        nonce = "".join(lst)
        bnonce =  base64.b64encode(nonce)
        args = {"nonce": bnonce}
        f = open(noncefile,"w")
        print "# Nonce for this quote is :"
        f.write(nonce)
        f.close()
        print nonce
    except:
        print "Error generating Nonce "
        raise
    try:
        ret_val = session.xenapi.host.call_plugin(host_ref, 'tpmGetQuote', 'main', args)
        quote = base64.b64decode(ret_val)
        f = open(quotein,"w")
        f.write(quote)
        f.close()
    except:
        print "Unable to Get Quote from Xenserver"
        print '## XEN TPM plugins may not be installed ##'
        raise
    try:
        r = call_exec()
        f = open(quoteout,"r")
        print f.read()
        f.close()
        if (r > 0 ):
            print 'Unable to Verify Quote\n'
        else:
            print 'Quote Verified \n'
    except:
        print 'Unbale to Execute xenqverify. did you Make ??  \n'
    try:
        os.rename(quoteout,"quote.last")
    except:
        pass
if __name__ == "__main__":
    if len(sys.argv) <> 4:
		print "Usage:"
		print sys.argv[0], "<XenServer host> <username> <password>"
		sys.exit(1)
    url = "https://" + sys.argv[1]
    username = sys.argv[2]
    password = sys.argv[3]
    session = XenAPI.Session(url)
    session.xenapi.login_with_password(username, password)
    try:
        main(session)
    except Exception, e:
        print str(e)
        raise

